#!/bin/sh

set -e
umask 027

# Create a tmp folder
TMPDIR="$SNAP_COMMON/tmp"
mkdir -p -m 750 $TMPDIR

SERVER_CONF="$SNAP_DATA/server.conf"
START_CONF="$SNAP_DATA/start.conf"
CONFIG_MARK="$SNAP_DATA/version.2"

SPREED_WEBRTC_PID="$SNAP_DATA/spreed.pid"

TLS_DAYS=3650
TLS_BITS=2048

OPENSSL="/usr/bin/openssl"
RANDFILE="$SNAP_DATA/.rnd"
export RANDFILE

cleanup () {
	trap "" EXIT
	echo "Stopping ..."
	if [ -n "$SPREED_WEBRTC_PID" ]; then
		kill -TERM $SPREED_WEBRTC_PID 2>/dev/null
	fi
	rm -f "$TMPDIR/spreed-webrtc.conf"
	echo "Done."
}
trap "cleanup" INT QUIT TERM EXIT

config () {
	if [ ! -e "$START_CONF" -o ! -e "$SERVER_CONF" -o ! -e "$CONFIG_MARK" ]; then
		echo "Updating configuraion ..."
		"$SNAP/bin/config" update >/dev/null
		touch "$CONFIG_MARK"
	fi
	if [ -e "$START_CONF" ]; then
		. "$START_CONF"
	fi
}

# Create random strings.
#sessionSecret=$($OPENSSL rand -hex 32)
#encryptionSecret=$($OPENSSL rand -hex 24)
#serverToken=$($OPENSSL rand -hex 16)

spreed_webrtc () {
	# Create runtime configuration.
	sed "\
	s|root = .*|root = $SNAP/share/spreed-webrtc-server/www|; \
	s|extra = .*|extra = $SNAP/extra|; \
	" $SERVER_CONF > "$TMPDIR/spreed-webrtc.conf"

	"$SNAP/sbin/spreed-webrtc-server" -c "$TMPDIR/spreed-webrtc.conf" &
	SPREED_WEBRTC_PID=$!
}

config
spreed_webrtc

echo "Running $SPREED_WEBRTC_PID ..."
wait $SPREED_WEBRTC_PID
